package com.cropdoctor.service.impl;

import com.cropdoctor.mapper.SysRolePermissionRelationMapper;
import com.cropdoctor.mapper.SysPermissionMapper;
import com.cropdoctor.model.po.SysPermissionPo;
import com.cropdoctor.model.po.SysRolePermissionRelationPo;
import com.cropdoctor.service.SysRolePermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysRolePermissionServiceImpl implements SysRolePermissionService {
    @Autowired
    private SysRolePermissionRelationMapper sysRolePermissionRelationMapper;
    @Autowired
    private SysPermissionMapper sysPermissionMapper;

    @Override
    public List<SysPermissionPo> getPermissionsByRoleId(Integer roleId) {
        List<SysRolePermissionRelationPo> relations = sysRolePermissionRelationMapper.selectList(
            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<SysRolePermissionRelationPo>().eq("role_id", roleId)
        );
        if(relations.isEmpty()) return java.util.Collections.emptyList();
        List<Integer> permissionIds = relations.stream().map(SysRolePermissionRelationPo::getPermissionId).collect(Collectors.toList());
        return sysPermissionMapper.selectBatchIds(permissionIds);
    }

    @Override
    public void setPermissionsForRole(Integer roleId, List<Integer> permissionIds) {
        // 先删除原有关系
        sysRolePermissionRelationMapper.delete(new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<SysRolePermissionRelationPo>().eq("role_id", roleId));
        // 再插入新关系
        for(Integer pid : permissionIds) {
            SysRolePermissionRelationPo relation = new SysRolePermissionRelationPo();
            relation.setRoleId(roleId);
            relation.setPermissionId(pid);
            sysRolePermissionRelationMapper.insert(relation);
        }
    }

    @Override
    public List<Integer> getPermissionIdsByRoleId(Integer roleId) {
        List<SysRolePermissionRelationPo> relations = sysRolePermissionRelationMapper.selectList(
            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<SysRolePermissionRelationPo>().eq("role_id", roleId)
        );
        return relations.stream().map(SysRolePermissionRelationPo::getPermissionId).collect(Collectors.toList());
    }
} 